<!DOCTYPE html><!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--><!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]--><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  
  <link rel="canonical" href="https://sequelize.org/v3/docs/docs/transactions/">
  <link rel="shortcut icon" href="/v3/favicon.ico">
  
  <title>Transactions - Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700">

  <link rel="stylesheet" href="/v3/css/theme.css">
  <link rel="stylesheet" href="/v3/css/theme_extra.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/github.min.css">
  <link href="/v3/css/custom.css" rel="stylesheet">
  
  <script>
    // Current page data
    var mkdocs_page_name = "Transactions";
    var mkdocs_page_input_path = "docs/transactions.md";
    var mkdocs_page_url = "/v3/docs/transactions/";
  </script>
  
  <script src="/v3/js/jquery-2.1.1.min.js" defer=""></script>
  <script src="/v3/js/modernizr-2.8.3.min.js" defer=""></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script> 
<meta name="robots" content="noindex"></head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
    <div class="wy-side-scroll">
      <div class="wy-side-nav-search">
        <a href="/v3" class="icon icon-home"> Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
        <div role="search">
  <form id="rtd-search-form" class="wy-form" action="/v3/search.html" method="get">
      <input type="text" name="q" placeholder="Search docs" title="Type search term here">
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3">Home</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Documentation</span></p>
                <ul class="current">
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/getting-started/">Getting Started</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/schema/">Working with table schemas</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="#">Models</a>
    <ul>
                <li class="toctree-l2"><a class="reference internal" href="/v3/docs/models-definition/">Definition</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/docs/models-usage/">Usage</a>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/querying/">Querying</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/scopes/">Scopes</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/instances/">Instances</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/associations/">Relations / Associations</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1 current"><a class="reference internal current" href="./">Transactions</a>
    <ul class="current">
    <li class="toctree-l2"><a class="reference internal" href="#throw-errors-to-rollback">Throw errors to rollback</a>
    </li>
    <li class="toctree-l2"><a class="reference internal" href="#automatically-pass-transactions-to-all-queries">Automatically pass transactions to all queries</a>
    </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/legacy/">Working with legacy tables</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/raw-queries/">Raw queries</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/migrations/">Migrations</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">API</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/sequelize/">Sequelize</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/model/">Model</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/instance/">Instance</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="#">Associations</a>
    <ul>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/">Overview</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to/">BelongsTo (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-one/">HasOne (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-many/">HasMany (1:m)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to-many/">BelongsToMany (n:m)</a>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/transaction/">Transaction</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/datatypes/">Datatypes</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/deferrable/">Deferrable</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/errors/">Errors</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Misc</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/changelog/">Changelog</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/imprint/">Imprint</a>
                    </li>
                </ul>
      </div>
    </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="/v3">Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
      </nav>

      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="/v3">Docs</a> »</li>
    
      
        
          <li>Documentation »</li>
        
      
    
    <li>Transactions</li>
    <li class="wy-breadcrumbs-aside">
      
        <a href="https://github.com/sequelize/sequelize/edit/master/docs/docs/transactions.md" class="icon icon-github"> Edit on GitHub</a>
      
    </li>
  </ul>
  
  <hr>
</div>

          <div role="main">
            <div class="section">
              
                <p>Sequelize supports two ways of using transactions:</p>
<ul>
<li>One which will automatically commit or rollback the transaction based on the result of a promise chain and, (if enabled) pass the transaction to all calls within the callback</li>
<li>And one which leaves committing, rolling back and passing the transaction to the user.</li>
</ul>
<p>The key difference is that the managed transaction uses a callback that expects a promise to be returned to it while the unmanaged transaction returns a promise.</p>
<h1 id="managed-transaction-auto-callback">Managed transaction (auto-callback)</h1>
<p>Managed transactions handle committing or rolling back the transaction automagically. You start a managed transaction by passing a callback to <code>sequelize.transaction</code>.</p>
<p>Notice how the callback passed to <code>transaction</code> returns a promise chain, and does not explicitly call <code>t.commit()</code> nor <code>t.rollback()</code>. If all promises in the returned chain are resolved successfully the transaction is committed. If one or several of the promises are rejected, the transaction is rolled back.</p>
<pre><code class="language-js">return sequelize.transaction(function (t) {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});
</code></pre>
<h3 id="throw-errors-to-rollback">Throw errors to rollback</h3>
<p>When using the managed transaction you should <em>never</em> commit or rollback the transaction manually. If all queries are successful, but you still want to rollback the transaction (for example because of a validation failure) you should throw an error to break and reject the chain:</p>
<pre><code class="language-js">return sequelize.transaction(function (t) {
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    // Woops, the query was successful but we still want to roll back!
    throw new Error();
  });
});
</code></pre>
<h3 id="automatically-pass-transactions-to-all-queries">Automatically pass transactions to all queries</h3>
<p>In the examples above, the transaction is still manually passed, by passing <code>{ transaction: t }</code> as the second argument. To automatically pass the transaction to all queries you must install the <a href="https://github.com/othiym23/node-continuation-local-storage">continuation local storage</a> (CLS) module and instantiate a namespace in your own code:</p>
<pre><code class="language-js">var cls = require('continuation-local-storage'),
    namespace = cls.createNamespace('my-very-own-namespace');
</code></pre>
<p>To enable CLS you must tell sequelize which namespace to use by setting it as a property on the sequelize constructor:</p>
<pre><code class="language-js">var Sequelize = require('sequelize');
Sequelize.cls = namespace;

new Sequelize(....);
</code></pre>
<p>Notice, that the <code>cls</code> property must be set on the <em>constructor</em>, not on an instance of sequelize. This means that all instances will share the same namespace, and that CLS is all-or-nothing - you cannot enable it only for some instances.</p>
<p>CLS works like a thread-local storage for callbacks. What this means in practice is, that different callback chains can access local variables by using the CLS namespace. When CLS is enabled sequelize will set the <code>transaction</code> property on the namespace when a new transaction is created. Since variables set within a callback chain are private to that chain several concurrent transactions can exist at the same time:</p>
<pre><code class="language-js">sequelize.transaction(function (t1) {
  namespace.get('transaction') === t1; // true
});

sequelize.transaction(function (t2) {
  namespace.get('transaction') === t2; // true
});
</code></pre>
<p>In most case you won't need to access <code>namespace.get('transaction')</code> directly, since all queries will automatically look for a transaction on the namespace:</p>
<pre><code class="language-js">sequelize.transaction(function (t1) {
  // With CLS enabled, the user will be created inside the transaction
  return User.create({ name: 'Alice' });
});
</code></pre>
<h1 id="concurrentpartial-transactions">Concurrent/Partial transactions</h1>
<p>You can have concurrent transactions within a sequence of queries or have some of them excluded from any transactions. Use the <code>{transaction: }</code> option to control which transaction a query belong to:</p>
<h3 id="without-cls-enabled">Without CLS enabled</h3>
<pre><code class="language-js">sequelize.transaction(function (t1) {
  return sequelize.transaction(function (t2) {
    // With CLS enable, queries here will by default use t2
    // Pass in the `transaction` option to define/alter the transaction they belong to.
    return Promise.all([
        User.create({ name: 'Bob' }, { transaction: null }),
        User.create({ name: 'Mallory' }, { transaction: t1 }),
        User.create({ name: 'John' }) // this would default to t2
    ]);
  });
});
</code></pre>
<h1 id="isolation-levels">Isolation levels</h1>
<p>The possible isolations levels to use when starting a transaction:</p>
<pre><code class="language-js">Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ  // "REPEATABLE READ"
Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"
</code></pre>
<p>By default, sequelize uses "REPEATABLE READ". If you want to use a different isolation level, pass in the desired level as the first argument:</p>
<pre><code class="language-js">return sequelize.transaction({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
  }, function (t) {

  // your transactions

  });
</code></pre>
<h1 id="unmanaged-transaction-then-callback">Unmanaged transaction (then-callback)</h1>
<p>Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call <code>sequelize.transaction()</code> without a callback (you can still pass an options object) and call <code>then</code> on the returned promise. Notice that <code>commit()</code> and <code>rollback()</code> returns a promise.</p>
<pre><code class="language-js">return sequelize.transaction().then(function (t) {
  return User.create({
    firstName: 'Homer',
    lastName: 'Simpson'
  }, {transaction: t}).then(function (user) {
    return user.addSibling({
      firstName: 'Lisa',
      lastName: 'Simpson'
    }, {transaction: t});
  }).then(function () {
    return t.commit();
  }).catch(function (err) {
    return t.rollback();
  });
});
</code></pre>
<h1 id="options">Options</h1>
<p>The <code>transaction</code> method can be called with an options object as the first argument, that
allows the configuration of the transaction.</p>
<pre><code class="language-js">return sequelize.transaction({ /* options */ });
</code></pre>
<p>The following options (with it's default values) are available:</p>
<pre><code class="language-js">{
  autocommit: true,
  isolationLevel: 'REPEATABLE_READ',
  deferrable: 'NOT DEFERRABLE' // implicit default of postgres
}
</code></pre>
<p>The <code>isolationLevel</code> can either be set globally when initializing the Sequelize instance or
locally for every transaction:</p>
<pre><code class="language-js">// globally
new Sequelize('db', 'user', 'pw', {
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});

// locally
sequelize.transaction({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
</code></pre>
<p>The <code>deferrable</code> option triggers an additional query after the transaction start
that optionally set the constraint checks to be deferred or immediate. Please note
that this is only supported in PostgreSQL.</p>
<pre><code class="language-js">sequelize.transaction({
  // to defer all constraints:
  deferrable: Sequelize.Deferrable.SET_DEFERRED,

  // to defer a specific constraint:
  deferrable: Sequelize.Deferrable.SET_DEFERRED(['some_constraint']),

  // to not defer constraints:
  deferrable: Sequelize.Deferrable.SET_IMMEDIATE
})
</code></pre>
<h1 id="usage-with-other-sequelize-methods">Usage with other sequelize methods</h1>
<p>The <code>transaction</code> option goes with most other options, which are usually the first argument of a method.
For methods that take values, like <code>.create</code>, <code>.update()</code>, <code>.updateAttributes()</code> etc. <code>transaction</code> should be passed to the option in the second argument.
If unsure, refer to the API documentation for the method you are using to be sure of the signature.</p>
              
            </div>
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="/v3/docs/legacy/" class="btn btn-neutral float-right" title="Working with legacy tables">Next <span class="icon icon-circle-arrow-right"></span></a>
      
      
        <a href="/v3/docs/hooks/" class="btn btn-neutral" title="Hooks"><span class="icon icon-circle-arrow-left"></span> Previous</a>
      
    </div>
  

  <hr>

  <div role="contentinfo">
    <!-- Copyright etc -->
    
  </div>

  Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
      
        </div>
      </div>

    </section>

  </div>

  <div class="rst-versions" role="note" aria-label="versions">
  <span class="rst-current-version" data-toggle="rst-current-version">
    
        <span>
          <a href="https://github.com/sequelize/sequelize/" class="fa fa-github" style="color: #fcfcfc"> GitHub</a>
        </span>
    
    
      <span><a href="/v3/docs/hooks/" style="color: #fcfcfc">« Previous</a></span>
    
    
      <span><a href="/v3/docs/legacy/" style="color: #fcfcfc">Next »</a></span>
    
  </span>
</div>
    <script>var base_url = '../..';</script>
    <script src="/v3/js/theme_extra.js" defer=""></script>
    <script src="/v3/js/theme.js" defer=""></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js" defer=""></script>
      <script src="/v3/search/main.js" defer=""></script>
    <script defer="">
        window.onload = function () {
            SphinxRtdTheme.Navigation.enable(true);
        };
    </script>



</body></html>